" vim: ft=vim
" Test the behaviors after a file is closed.

Before;
let file = tempname()
call writefile([], file)
let file_ = object#file_()
let closed_exception = 'OSError.*closed'
let content = 'Test Content'


Execute (After closed, repr displays 'closed file');
let f=object#open(file, 'r')
call f.close()
Assert object#repr(f) =~# 'closed'


Execute (After closed, read operation fails);
let readers = ['read', 'readline', 'readlines', '__iter__', 'readable']
let f=object#open(file, 'r')
call f.close()

for method in readers
  AssertThrows call g:f[g:method]()
  Log g:vader_exception
  Assert g:vader_exception =~# closed_exception
endfor


Execute (After closed, write operation fails);
let writers = ['write', 'writeline', 'writelines']
let f=object#open(file, 'w')
call f.write('Test')
call f.close()

for method in writers
  AssertThrows call g:f[g:method]('')
  Log g:vader_exception
  Assert g:vader_exception =~# closed_exception
endfor

for method in ['flush', 'writable']
  AssertThrows call g:f[g:method]()
  Assert g:vader_exception =~# closed_exception
endfor


Execute(After closed, contents are written to file);
let f=object#open(file, 'w')

call f.writeline(content)
call f.close()
AssertEqual readfile(f.name)[0], content


Execute(Throws OSError when flush fails);
let f=object#open(file, 'w')
call f.writeline(content)
call setfperm(f.name, 'r--------')

AssertThrows call g:f.close()
Log g:vader_exception
Assert g:vader_exception =~# 'OSError'


Execute(If close() or flush() is omitted, the file stays unmodified);
call writefile([content], file)
let f = object#open(file, 'w')
call f.write('This string is supposed to appear')
" f.close()
AssertEqual readfile(file)[0], content

After;
call delete(file)
